package com.liuweidihuangwan.jingdong.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liuweidihuangwan.jingdong.context.BaseContext;
import com.liuweidihuangwan.jingdong.exception.BusinessException;
import com.liuweidihuangwan.jingdong.exception.ErrorCode;
import com.liuweidihuangwan.jingdong.exception.ThrowUtils;
import com.liuweidihuangwan.jingdong.model.dto.address.AddressAddRequest;
import com.liuweidihuangwan.jingdong.model.dto.address.AddressDefaultRequest;
import com.liuweidihuangwan.jingdong.model.dto.address.AddressEditRequest;
import com.liuweidihuangwan.jingdong.model.entity.Userinfo;
import com.liuweidihuangwan.jingdong.model.enums.AddressStatus;
import com.liuweidihuangwan.jingdong.model.vo.AddressUserVO;
import com.liuweidihuangwan.jingdong.model.vo.AddressVO;
import com.liuweidihuangwan.jingdong.service.AddressService;
import com.liuweidihuangwan.jingdong.model.entity.Address;
import com.liuweidihuangwan.jingdong.mapper.AddressMapper;
import com.liuweidihuangwan.jingdong.service.UserinfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
* @author Administrator
* @description 针对表【address】的数据库操作Service实现
* @createDate 2025-01-08 11:47:22
*/
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address>
    implements AddressService {

    @Resource
    UserinfoService userinfoService;

    /**
     * 添加地址
     * @param addressAddRequest
     * @return
     */
    @Override
    public Integer addAddress(AddressAddRequest addressAddRequest) {
        //校验地址
        if(addressAddRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        String addressContent = addressAddRequest.getAddress();
        ThrowUtils.throwIf(addressContent == null,ErrorCode.PARAMS_ERROR,"传入地址为空");

        //将地址加入数据库
        Address address = new Address();
        Long userId = BaseContext.getCurrentId();
        address.setUserID(userId.intValue());
        address.setAddress(addressContent);
        address.setIsSelected(AddressStatus.NOT_SELECTED.getValues());

        boolean save = save(address);
        if(!save){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"添加地址失败");
        }
        return address.getAddressID();
    }

    /**
     * 查询用户的地址
     * @return
     */
    @Override
    public List<AddressVO> queryAddressList() {
        Long userId = BaseContext.getCurrentId();
        if(userId == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        //根据用户Id查询地址
        List<Address> addressList = lambdaQuery().eq(Address::getUserID, userId).list();

        List<AddressVO> addressVOS = new ArrayList<>();
        for (Address address : addressList) {
            AddressVO addressVO = new AddressVO();
            BeanUtils.copyProperties(address,addressVO);
            Userinfo userinfo = userinfoService.getById(userId);
            AddressUserVO addressUserVO = new AddressUserVO();
            BeanUtils.copyProperties(userinfo,addressUserVO);
            addressVO.setAddressUserVO(addressUserVO);
            addressVOS.add(addressVO);
        }
        return addressVOS;
    }

    /**
     * 编辑地址
     * @param addressEditRequest
     * @return
     */
    @Override
    public Integer editAddress(AddressEditRequest addressEditRequest) {
        //校验参数
        if(addressEditRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }

        Integer addressID = addressEditRequest.getAddressID();
        String addressContent = addressEditRequest.getAddress();

        if(addressContent == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"传入的地址为空");
        }

        Address address = new Address();
        address.setAddressID(addressID);
        address.setAddress(addressContent);

        boolean result = updateById(address);
        if(!result){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"编辑失败");
        }
        return addressID;
    }

    /**
     * 删除地址
     * @param addressId
     * @return
     */
    @Override
    public Integer deleteAddress(Integer addressId) {

        //校验参数
        if(addressId == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        Long userId = BaseContext.getCurrentId();
        if(userId == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        //查询数据库是否有该条数据
        //判断用户删除的数据是否是自己的
        boolean exists = lambdaQuery()
                .eq(Address::getAddressID, addressId)
                .eq(Address::getUserID, userId)
                .exists();
        if(!exists){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        boolean result = removeById(addressId);
        if(!result){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"删除失败");
        }
        return addressId;
    }

    /**
     * 将地址设置成默认
     * @param addressDefaultRequest
     * @return
     */
    @Override
    @Transactional
    public Integer setDefaultAddress(AddressDefaultRequest addressDefaultRequest) {
        //校验参数
        if(addressDefaultRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        Integer addressID = addressDefaultRequest.getAddressID();
        Integer isSelected = addressDefaultRequest.getIsSelected();

        if(addressID == null || isSelected == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }

        Long userId = BaseContext.getCurrentId();
        if(userId == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        //查询数据库，判断旧数据和修改的数据是否一致
        Address oldAddress = lambdaQuery()
                .eq(Address::getAddressID, addressID)
                .eq(Address::getUserID, userId)
                .one();

        if(oldAddress == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        Integer oldIsSelected = oldAddress.getIsSelected();
        if(Objects.equals(oldIsSelected, isSelected)){
            return addressID;
        }

        //判断如果取消默认还是选择默认
        if(Objects.equals(isSelected,AddressStatus.SELECTED.getValues())){
            //如果是选择默认
            //将该地址改为选择
            Address address = new Address();
            address.setAddressID(addressID);
            address.setIsSelected(isSelected);
            boolean result = updateById(address);
            if(!result){
                throw new BusinessException(ErrorCode.SYSTEM_ERROR,"系统错误");
            }
            //将除了该地址的其他地址改为不选择
            LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper
                    .ne(Address::getAddressID,addressID)
                    .eq(Address::getUserID,userId);
            Address address1 = new Address();
            address1.setIsSelected(AddressStatus.NOT_SELECTED.getValues());
            result = update(address1, queryWrapper);
            if(!result){
                throw new BusinessException(ErrorCode.SYSTEM_ERROR,"系统错误");
            }
        }else{
            //将地址改为非默认
            Address address = new Address();
            address.setAddressID(addressID);
            address.setIsSelected(isSelected);
            boolean result = updateById(address);
            if(!result){
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
        }
        return addressID;
    }
}




